package cn.com.czpb.client.module.newspager.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SynthesizerListener;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.com.czpb.client.R;
import cn.com.czpb.client.app.MToolBarActivity;
import cn.com.czpb.client.module.dialog.ShareDialog;
import cn.com.czpb.client.utils.FjsonUtil;
import cn.com.czpb.client.utils.LogUtils;
import cn.com.czpb.client.utils.PageCtrl;

import butterknife.BindView;
import cn.com.czpb.client.utils.StringUtils;
import cn.com.czpb.client.utils.TUtils;

/**
 * Created by 猪猪侠 on 2017/10/30.
 */

public class NewspagerActivity extends MToolBarActivity {
    @BindView(R.id.webview_news_szb)
    WebView mWebView;
    @BindView(R.id.img_activity_back)
    ImageView img_activity_back;
    @BindView(R.id.img_web_back)
    ImageView img_web_back;
    @BindView(R.id.img_share_newspaper)
    ImageView img_share_newspaper;



    @BindView(R.id.ll_bottom_id)
    LinearLayout ll_bottom_id;

    @BindView(R.id.img_play_id)
    ImageView img_play_id;
    @BindView(R.id.tv_title_id)
    TextView tvTitleId;
    @BindView(R.id.tv_double_id)
    TextView tvDoubleId;
    @BindView(R.id.tv_time_id)
    TextView tvTimeId;

    private String url;


    int t = 60;
    private Timer timer;
    private boolean isPlay = false;
    private SpeechSynthesizer mTts;
    private String[] items_double= new String[]{"0.8X", "1X","1.5X","2X"};
    private String[] items_time= new String[]{"5分钟后", "15分钟后","30分钟后","不开启定时"};
    //    private boolean isFirst = true;
    // 引擎类型
    private String mEngineType = SpeechConstant.TYPE_CLOUD;
    //发音人
    private int selectedNum = 0;
    // 默认发音人
    private String voicer = "xiaoyan";
    private String content;
    private static final String TAG = "NewsDetailActivity";


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (333 == msg.what) {
                try {
                    tvTimeId.setText(t + "'");
                    t--;
                    if (t < 0) {
                        resetTimer();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
            if (666 == msg.what) {
                try {
                    firstPlay();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
            if (777 == msg.what) {
//                if (spu.getUser() == null) {
//                    PageCtrl.start2LoginActivity((Activity) mContext);
//                }

            }
//            if (888 == msg.what) {
//                    //作者个人主页
////                 String uid = msg.getData().getString("uid");
////                 String tid = msg.getData().getString("tid");
//                    PageCtrl.start2SubscribeDetailActivity(activity,uid,tid);
//
//            }
        }
    };


    @Override
    protected int setLayoutId() {
        return R.layout.activity_newspager_detail;
    }

    @Override
    public void initView() {

        Intent intent = getIntent();
        url = intent.getStringExtra("url");
        WebSettings webSettings = mWebView.getSettings();
        String ua = webSettings.getUserAgentString();
        LogUtils.i("ua-->" + ua);
        webSettings.setUserAgentString(ua + "; gxrbapp/");
        String ua2 = webSettings.getUserAgentString();
        LogUtils.i("ua-->" + ua2);
        webSettings.setSavePassword(false);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setAppCacheEnabled(true);
        mWebView.addJavascriptInterface(this, "szbListner");
        mWebView.addJavascriptInterface(this, "sendsong");

        mWebView.setVerticalScrollBarEnabled(false); //垂直不显示
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }
        });
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        //语音功能
        mTts = SpeechSynthesizer.createSynthesizer(activity,null);
    }

    @Override
    public void onBackPressed() {
        if (mWebView.canGoBack() && mWebView.getUrl().contains("date")) {
            mWebView.goBack();
        } else {
            finish();
        }

    }

    @OnClick({R.id.img_activity_back, R.id.img_web_back, R.id.img_share_newspaper,R.id.img_close_id,R.id.tv_double_id,R.id.tv_time_id})
    public void dobackorshare(View view) {
        switch (view.getId()) {
            case R.id.img_activity_back:
                finish();
                break;
            case R.id.img_web_back:
                onBackPressed();
                break;
            case R.id.img_share_newspaper:
//                Uri uri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + r.getResourcePackageName(R.drawable.redclouds) + "/" + r.getResourceTypeName(R.drawable.redclouds) + "/" + r.getResourceEntryName(R.drawable.redclouds));

                ShareDialog dialog = new ShareDialog(activity, R.style.Sharedialog, mWebView.getTitle(), mWebView.getUrl(), getResources().getString(R.string.shared_img), 1);

                dialog.show();
                break;
            case R.id.img_close_id:
                //隐藏关闭读报
//                isFirst =true;
                mTts.stopSpeaking();
//                home_read.setImageResource(R.drawable.read1);
                ll_bottom_id.setVisibility(View.GONE);
                img_play_id.setImageResource(R.drawable.start);
                break;
            case R.id.tv_double_id:
                new AlertDialog.Builder(activity).
                        setTitle("语速设置")
                        .setItems(items_double, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                switch (i){
                                    case 0:
                                        tvDoubleId.setText("0.8X");
                                        spu.setSpeed("40");
                                        firstPlay();
                                        break;
                                    case 1:
                                        tvDoubleId.setText("1.0X");
                                        spu.setSpeed("50");
                                        firstPlay();
                                        break;
                                    case 2:
                                        tvDoubleId.setText("1.5X");
                                        spu.setSpeed("75");
                                        firstPlay();
                                        break;
                                    case 3:
                                        tvDoubleId.setText("2.0X");
                                        spu.setSpeed("100");
                                        firstPlay();
                                        break;
                                }
                            }
                        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                    }
                }).setCancelable(true).show();
                break;
            case R.id.tv_time_id:
                new AlertDialog.Builder(activity).
                        setTitle("选择关闭时间")
                        .setItems(items_time, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                switch (i){
                                    case 0:
                                        tvTimeId.setText("5'");
                                        startTime();
                                        t=5;
                                        break;
                                    case 1:
                                        tvTimeId.setText("15'");
                                        t=15;
                                        startTime();
                                        break;
                                    case 2:
                                        tvTimeId.setText("30'");
                                        t=30;
                                        startTime();
                                        break;
                                    case 3:
                                        tvTimeId.setText("定时");
                                        if (null==timer){
                                            return;
                                        }
                                        timer.cancel();
                                        break;
                                }
                            }
                        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                    }
                }).setCancelable(true).show();
                //开启倒计时
                LogUtils.i("5秒倒计时");
                break;
            case R.id.img_play_id:
                //播放
                if (isPlay){
//                    home_read.setImageResource(R.drawable.read1);
                    img_play_id.setImageResource(R.drawable.start);
                    mTts.pauseSpeaking();
                    isPlay =false;
                }else {
//                    Glide.with(this).load(R.drawable.read1_gif).into(home_read);
                    Glide.with(this).load(R.drawable.bof_gif).asGif().into(img_play_id);
                    mTts.resumeSpeaking();
                    isPlay =true;
                }
                break;

        }
    }


    @Override
    public void initData() {
        switch (spu.getSpeed()){
            case "40":
                tvDoubleId.setText("0.8X");
                break;
            case "50":
                tvDoubleId.setText("1.0X");
                break;
            case "75":
                tvDoubleId.setText("1.5X");
                break;
            case "100":
                tvDoubleId.setText("2.0X");
                break;

            default:
                tvDoubleId.setText("1.0X");
                break;
        }

//        mWebView.loadUrl("http://nj.99cms.com/demo//web/GJSB_SZB/2016-12/08/7875.html");
        mWebView.loadUrl(url);
    }

    @JavascriptInterface
    public void getInfo(String info) {
        LogUtils.e("getInfo-->" + info);
        JSONObject object = FjsonUtil.parseObject(info);
        String title = object.getString("title");
        String url = object.getString("url");
        LogUtils.e("title-->" + title);
        LogUtils.e("url-->" + url);
        PageCtrl.start2NewsPagerDetailActivity(activity, url, title);

    }

    @JavascriptInterface
    public void getContent(String info) {
        handler.sendEmptyMessage(666);
        content=info;
    }

    @Override
    public void finish() {
        if (mTts!=null){
            mTts.stopSpeaking();
        }

        super.finish();
    }
    private void resetTimer() {
        if (null==timer){
            return;
        }
        timer.cancel();
        tvTimeId.setText("定时");
//        isFirst =true;
        //隐藏关闭读报
        mTts.stopSpeaking();
        ll_bottom_id.setVisibility(View.GONE);
    }

    public  void playMusic(){


        if (  StringUtils.isEmpty(content) ){

            return;
        }


        mTts.startSpeaking(content,mTtsListener);
//        Glide.with(this).load(R.drawable.read1_gif).into(home_read);
        Glide.with(this).load(R.drawable.bof_gif).asGif().into(img_play_id);
    }

    public void firstPlay(){
        LogUtils.i("play-->2");
        ll_bottom_id.setVisibility(View.VISIBLE);
        isPlay =true;
//        isFirst = false;
        setParam();
        playMusic();

    }
    private void startTime() {
        if (timer!=null){
            timer.cancel();
        }
        timer=new Timer();
        TimerTask tt=new TimerTask() {
            @Override
            public void run() {
                handler.sendEmptyMessage(333);
            }
        };
        timer.schedule(tt,0,5000);
    }




    //语音功能
    /**
     * 参数设置
     * @return
     */
    private void setParam(){
        // 清空参数
        if (null!=mTts){
            mTts.setParameter(SpeechConstant.PARAMS, null);
        }else {
            mTts = SpeechSynthesizer.createSynthesizer(activity,null);
        }
        // 根据合成引擎设置相应参数
        if(mEngineType.equals(SpeechConstant.TYPE_CLOUD)) {
            mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD);
            // 设置在线合成发音人
            mTts.setParameter(SpeechConstant.VOICE_NAME, voicer);
            //设置合成语速
            mTts.setParameter(SpeechConstant.SPEED, spu.getSpeed());
            //设置合成音调
            mTts.setParameter(SpeechConstant.PITCH, "50");
            //设置合成音量
            mTts.setParameter(SpeechConstant.VOLUME,  "50");
        }
        else {
            mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_LOCAL);
            // 设置本地合成发音人 voicer为空，默认通过语记界面指定发音人。
            mTts.setParameter(SpeechConstant.VOICE_NAME, "");
            /**
             * TODO 本地合成不设置语速、音调、音量，默认使用语记设置
             * 开发者如需自定义参数，请参考在线合成参数设置
             */
        }
        //设置播放器音频流类型
        mTts.setParameter(SpeechConstant.STREAM_TYPE, "3");
        // 设置播放合成音频打断音乐播放，默认为true
        mTts.setParameter(SpeechConstant.KEY_REQUEST_FOCUS, "true");

        // 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
        // 注：AUDIO_FORMAT参数语记需要更新版本才能生效
        mTts.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");
        mTts.setParameter(SpeechConstant.TTS_AUDIO_PATH, Environment.getExternalStorageDirectory()+"/msc/tts.wav");
    }
    /**
     * 合成回调监听。
     */
    private SynthesizerListener mTtsListener = new SynthesizerListener() {

        @Override
        public void onSpeakBegin() {
            Log.e(TAG, "onSpeakBegin:开始播放 ", null);
        }

        @Override
        public void onSpeakPaused() {
            Log.e(TAG, "onSpeakBegin:暂停播放 ", null);
//            showTip("暂停播放");
        }

        @Override
        public void onSpeakResumed() {
            Log.e(TAG, "onSpeakBegin:继续播放 ", null);
//            showTip("继续播放");
        }

        @Override
        public void onBufferProgress(int percent, int beginPos, int endPos,
                                     String info) {
            // 合成进度
//            mPercentForBuffering = percent;
//            showTip(String.format(getString(R.string.tts_toast_format),
//                    mPercentForBuffering, mPercentForPlaying));
        }

        @Override
        public void onSpeakProgress(int percent, int beginPos, int endPos) {
            // 播放进度
//            mPercentForPlaying = percent;
//            showTip(String.format(getString(R.string.tts_toast_format),
//                    mPercentForBuffering, mPercentForPlaying));
        }

        @Override
        public void onCompleted(SpeechError error) {
            if (error == null) {
                mTts.stopSpeaking();
                ll_bottom_id.setVisibility(View.GONE);
            }
        }

        @Override
        public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
            // 以下代码用于获取与云端的会话id，当业务出错时将会话id提供给技术支持人员，可用于查询会话日志，定位出错原因
            // 若使用本地能力，会话id为null
            //	if (SpeechEvent.EVENT_SESSION_ID == eventType) {
            //		String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID);
            //		Log.d(TAG, "session id =" + sid);
            //	}
        }
    };

    public void playMMusic(){
//    LogUtils.i("play-->3"+isFirst);
//    if (isFirst){
//        firstPlay();
//    }else{
        if (isPlay){
//            home_read.setImageResource(R.drawable.read1);
            img_play_id.setImageResource(R.drawable.start);
            mTts.pauseSpeaking();
            isPlay =false;
        }else {
//            Glide.with(this).load(R.drawable.read1_gif).into(home_read);
            Glide.with(this).load(R.drawable.bof_gif).asGif().into(img_play_id);
            mTts.resumeSpeaking();
            isPlay =true;
        }
    }
    //}

    public void playMM() {

//        if (isFirst){
//            firstPlay();
//        }else{
        if (isPlay){
//                home_read.setImageResource(R.drawable.read1);
            img_play_id.setImageResource(R.drawable.start);
            mTts.pauseSpeaking();
            isPlay =false;
        }else {
//                Glide.with(this).load(R.drawable.read1_gif).into(home_read);
            Glide.with(this).load(R.drawable.bof_gif).asGif().into(img_play_id);
            mTts.resumeSpeaking();
            isPlay =true;
        }
//        }
    }
}

